package controller.user_management;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.group_management.AddMemberToGroupAdapter;
import adapter.user_management.AllTabInUserManagementFragmentAdapter;
import adapter.user_management.CompanyManagerTabInUserManagementFragmentAdapter;
import adapter.user_management.GeneralUserTabInUserManagementFragmentAdapter;
import adapter.user_management.GroupManagerTabInUserManagementFragmentAdapter;
import adapter.user_management.SuggestUserInInviteUserToCompanyAdapter;
import define.API;
import define.Key;
import model.user_management.AllTabInUserManagementItem;
import ui.activity.user_managament.InviteUserToCompany;
import ui.fragment.company.CompanyFeedFragment;
import ui.fragment.group_management.AddMemberToGroupFragment;
import ui.fragment.user_management.AllTabInUserManagementFragment;
import ui.fragment.user_management.CompanyManagerTabInUserManagementFragment;
import ui.fragment.user_management.GeneralUserTabInUserManagementFragment;
import ui.fragment.user_management.GroupManagerTabInUserManagementFragment;
import ui.fragment.user_management.UserManagementFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class InviteUserToCompanyAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */

    private String ERROR = "";
    private String STATUS = "";
    private String MSG = "";

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;

    public InviteUserToCompanyAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext.getApplicationContext(), ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext.getApplicationContext(), MSG ,
                    Toast.LENGTH_SHORT).show();
//            //reset user management
//            UserManagementFragment.setDataForUserManagementFragment();
            //reset data in mAlInviteUserEmail
            if (!InviteUserToCompany.mAlInviteUserEmail.isEmpty()) {
                InviteUserToCompany.mAlInviteUserEmail.clear();
            }
            //reset data array check box checked
            if (!SuggestUserInInviteUserToCompanyAdapter.mAlPosOfItemCheckedInSuggestUser.isEmpty())
                SuggestUserInInviteUserToCompanyAdapter.mAlPosOfItemCheckedInSuggestUser.clear();
            //enable text view invite user to company, avoid user click much times
            InviteUserToCompany.mTvInviteInInviteUserToCompany.setEnabled(true);
            //use context of enterprise activity to transfer fragment
            ((FragmentActivity) Enterprise.mContext).getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_in_activity_enterprise, CompanyFeedFragment.newInstance())
                    .commitAllowingStateLoss();
            //set title for action bar
            Enterprise.mTvTitle.setText(Enterprise.company.getCompanyNameSelected());
            //finish invite user to company page and go to home page
            ((Activity) mContext).finish();
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.INVITE_USER_TO_JOIN_COMPANY);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.USER_EMAILS, params[1]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_NAME, params[3]));
        mListValues.add(new BasicNameValuePair(Key.ROLE, params[4]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", InviteUserToCompanyAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                MSG = mJoXml.getString(Key.MSG);
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}